<?php

require_once 'ActionFramework/start.php';
require_once '3rd_party/recaptcha/recaptchalib.php';
require_once 'views/all.cls.php';

require_once 'actions/_user_settings.cls.php';

/**
 * Create the new account.
 */
class FinishSignupAction extends _UserSettingsAction {
	
	const INPUT_SECRET = "secret";
	const INPUT_CAPTCHA_CHALLENGE = "recaptcha_challenge_field";
	const INPUT_CAPTCHA_RESPONSE = "recaptcha_response_field";
	
	public function __construct() {
		parent::__construct();
		$this->add_profile_inputs();
		$this->add_criteria_inputs();
		$this->add_password_input();
		$this->add_input(FinishSignupAction::INPUT_SECRET);
		$this->add_input(FinishSignupAction::INPUT_CAPTCHA_CHALLENGE);
		$this->add_input(FinishSignupAction::INPUT_CAPTCHA_RESPONSE);
	}
	
	public function trigger($request) {
		
		$secret = $request[FinishSignupAction::INPUT_SECRET];
		
		// Use post: explicitly required according to the recaptcha docs
		$recaptcha_answer = recaptcha_check_answer(
			RECAPTCHA_PRIVATE_KEY,
			$_SERVER["REMOTE_ADDR"],
			$_POST[FinishSignupAction::INPUT_CAPTCHA_CHALLENGE],
			$_POST[FinishSignupAction::INPUT_CAPTCHA_RESPONSE]
		);
		
		global $DB;
		// This should never be the case unless people try to hack things
		if (!$DB->signup_secret_exists($secret)){
			$start_action = new StartAction();
			$view = $start_action->trigger($request);
			$view->add_message("Invalid sign-up code.");
			return $view;
		}
		$signup_user_data = $DB->get_signup_user_data($secret);
		
		// Just to be sure. Multiple signup-accounts can be created with the same email address 
		// (e.g. for when the email is lost somehow), but only once it can become an actual user.
		if ($DB->is_email_known($signup_user_data['email'])) {
			return r(new StartAction("Registration failed, because this email address is already in use."))->trigger($request);
		}
		
		$data = array_merge(
					$this->extract_profile_inputs($request),
					$this->extract_criteria_inputs($request),
					$this->extract_password_inputs($request),
					array(User::email => $signup_user_data[User::email])
		);
		
		// Recaptcha
		if (!$recaptcha_answer->is_valid) {
			// Create a user to pass in to the signup form
			$view = new ContinueSignupView(
				$secret, 
				$data[_UserSettingsAction::INPUT_FIRST_NAME], 
				new User($data)
			);
			$view->add_message('The reCaptcha verification failed. Would you mind trying again?');
			return $view;
		}
		
		$_SESSION['user'] = $DB->create_user($data);
		$DB->remove_signup_user($secret);
		
		$view = r(new ViewMatchingAction())->trigger($request);
		$view->add_message("Your account has been created. Good luck!");
		return $view;
	}
}

?>